package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.CommentAdapter;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.TeamLinGanAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.WebAppInterface.webCallBack;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.NoScrollListView;
import com.jml.zlhq.app.widgets.ObservableScrollView;
import com.jml.zlhq.app.widgets.ObservableScrollView.ScrollViewListener;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class TeamDetailActivity extends BaseActivity {
	
	private LinearLayout pinglun,phone;
	private RelativeLayout header;
	private int topPicH;
	private ObservableScrollView scrollView;
	private String id;
	private String tel;
	
	public webCallBack share,collect;
	private boolean collected = false;
	private ImageView fx;
	
	private ImageView image,icon,vip,zan,map;
	private RelativeLayout imglay;
	@SuppressWarnings("unused")
	private LinearLayout story,awards,awesome,works,comment,contact;
	private TextView storyText,awardsText,title,titleInfo,pinfen,dianpins,souchang,contactinfo,contactphon,inshare,incollect,allwork;
	private ListView worklistview,conmentlistview;
	private TextView nocomment;
	private IBaseAdapter workAdapter,conmentAdapter;
	private List<JSONObject> worklist = new ArrayList<JSONObject>();
	private List<JSONObject> conmentlist = new ArrayList<JSONObject>();
	
	private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
        	if(msg.what==1){
				try {
					String data = msg.getData().getString("data");
					final JSONObject json = new JSONObject(data);
					ImageLoader.getInstance().displayImage(BaseTools.getFrom("cover.image_url", json), image, UIUtil.getImageLoaderDisplayOptions(R.drawable.default640_320));
					ImageLoader.getInstance().displayImage(BaseTools.getFrom("logo_url.image_url", json), icon, UIUtil.getImageLoaderDisplayOptions(R.drawable.default140));
					title.setText(BaseTools.getFrom("name", json));
					titleInfo.setText(BaseTools.getFrom("location", json));
					
					collected = !StringUtil.isEmpty(BaseTools.getFrom("is_collect",json))&&BaseTools.getFrom("is_collect",json).equals("true");
					fx.setImageResource(collected?R.drawable.ico_save_full:R.drawable.collect_selector);
					
					if(StringUtil.isEmpty(BaseTools.getFrom("user.isAwesome", json))||Integer.parseInt(BaseTools.getFrom("awesome.isAwesome", json))==0){
						zan.setVisibility(View.GONE);
					}else{
						zan.setVisibility(View.VISIBLE);
					}
					if(StringUtil.isEmpty(BaseTools.getFrom("user.isVerify", json))||Integer.parseInt(BaseTools.getFrom("isVerify", json))==0){
						vip.setVisibility(View.GONE);
					}else{
						vip.setVisibility(View.VISIBLE);
					}
					
					if(StringUtil.isEmpty(BaseTools.getFrom("description", json))){
						story.setVisibility(View.GONE);
					}else{
						storyText.setText(BaseTools.getFrom("description", json));
					}
					JSONArray awardsArr = json.getJSONArray("awards");
					if(awardsArr==null||awardsArr.length()==0){
						awards.setVisibility(View.GONE);
					}else{
						String awardsStr = "";
						for (int i = 0; i < awardsArr.length(); i++) {
							awardsStr += StringUtil.isEmpty(awardsStr)?awardsArr.getString(i):"\n"+awardsArr.getString(i);
						}
						awardsText.setText(awardsStr);
					}
					if(StringUtil.isEmpty(BaseTools.getFrom("awesome.isAwesome", json))||BaseTools.getFrom("awesome.isAwesome", json).equals("0")){
						awesome.setVisibility(View.GONE);
					}
					
					final JSONArray worksArr = json.getJSONArray("works");
					worklist.clear();
					if(worksArr==null||worksArr.length()==0){
						works.setVisibility(View.GONE);
					}else{
						for (int i = 0; i < worksArr.length()&&i<4; i++) {
							worklist.add(worksArr.getJSONObject(i));
						}
					}
					workAdapter.notifyDataSetChanged();
					
					JSONArray contactsArr = null;
					try {
						contactsArr = json.getJSONArray("contacts");
					} catch (Exception e) {}
					String contactsStr = "";
					for (int i = 0; i < contactsArr.length(); i++) {
						String ifn = BaseTools.getFrom("type", contactsArr.getJSONObject(i))+"："+BaseTools.getFrom("name", contactsArr.getJSONObject(i));
						contactsStr += StringUtil.isEmpty(contactsStr)?ifn:"\n"+ifn;
					}
					String ifn = "地址："+BaseTools.getFrom("address.name", json);
					contactsStr += StringUtil.isEmpty(contactsStr)?ifn:"\n"+ifn;
					contactinfo.setText(contactsStr);
					
					tel = BaseTools.getFrom("phone", json);
					String ifp = "电话："+tel;
					contactphon.setText(ifp);
					ImageLoader.getInstance().displayImage(BaseTools.getFrom("local_image", json), map, UIUtil.getImageLoaderDisplayOptions(R.drawable.default640_320));
					
					JSONArray commentsArr = null;
					try {
						commentsArr = json.getJSONArray("comments");
					} catch (Exception e) {}
					conmentlist.clear();
					for (int i = 0; commentsArr!=null && i < commentsArr.length(); i++) {
						conmentlist.add(commentsArr.getJSONObject(i));
					}
					conmentAdapter.notifyDataSetChanged();
					nocomment.setVisibility(conmentlist.isEmpty()?View.VISIBLE:View.GONE);
					
					pinfen.setText(BaseTools.getFrom("score", json));
					dianpins.setText(BaseTools.getFrom("statistic.COMMENT", json));
					souchang.setText(BaseTools.getFrom("statistic.COLLECT", json));
				
					pinglun.setOnClickListener(TeamDetailActivity.this);
					phone.setOnClickListener(TeamDetailActivity.this);
					inshare.setOnClickListener(TeamDetailActivity.this);
					incollect.setOnClickListener(TeamDetailActivity.this);
					if(worksArr!=null&&worksArr.length()>4){
						allwork.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Bundle data = new Bundle();
								data.putString("json", worksArr.toString());
								UIUtil.openActivity(activity, AllWorkActivity.class, data);
							}
						});
					}else{
						allwork.setVisibility(View.GONE);
					}
					map.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							Bundle data = new Bundle();
							data.putString("latitude", BaseTools.getFrom("address.latitude",json));
							data.putString("longitude", BaseTools.getFrom("address.longitude",json));
							//UIUtil.openActivity(activity, MapActivity.class, data);
						}
					});
				} catch(Exception e){
					e.printStackTrace();
				}
			}
        	if(msg.what==2){
        		fx.setImageResource(collected?R.drawable.ico_save_full:R.drawable.collect_selector);
        	}
        }  
	}; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.team_detail_activity);
		
		scrollView = (ObservableScrollView) findViewById(R.id.team_detail_scroll);
		scrollView.smoothScrollTo(0, 0);
		topPicH = (int) (UIUtil.winWidth*336/640);
		scrollView.setScrollViewListener(new ScrollViewListener() {
			
			@Override
			public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
					int oldx, int oldy) {
				int alpha = y*255/topPicH;
				alpha = alpha>220?220:alpha;
				alpha = alpha<0?0:alpha;
				header.getBackground().setAlpha(alpha);
			}
		});
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setImageResource(R.drawable.share_selector);
		fx = (ImageView) findViewById(R.id.content_header_right_img2);
		fx.setVisibility(View.VISIBLE);
		fx.setImageResource(R.drawable.collect_selector);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setVisibility(View.INVISIBLE);
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		roghtImage1.setOnClickListener(this);
		fx.setOnClickListener(this);
		
		header = (RelativeLayout) findViewById(R.id.content_header);
		header.setBackgroundColor(getResources().getColor(R.color.black));
		header.getBackground().setAlpha(0);
		
		image = (ImageView) findViewById(R.id.team_detail_img);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,topPicH);
		image.setLayoutParams(lp);
		icon = (ImageView) findViewById(R.id.team_detail_icon);
		imglay = (RelativeLayout) findViewById(R.id.team_detail_imglay);
		LinearLayout.LayoutParams ilp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,UIUtil.winWidth*336/640+UIUtil.dip2px(activity, 17));
		imglay.setLayoutParams(ilp);
		
		story = (LinearLayout) findViewById(R.id.team_detail_story);
		awards = (LinearLayout) findViewById(R.id.team_detail_awards);
		awesome = (LinearLayout) findViewById(R.id.team_detail_awesome);
		works = (LinearLayout) findViewById(R.id.team_detail_works);
		comment = (LinearLayout) findViewById(R.id.team_detail_commentlay);
		contact = (LinearLayout) findViewById(R.id.team_detail_contact);
		
		nocomment = (TextView) findViewById(R.id.team_detail_nocomment);
		
		contactinfo = (TextView) findViewById(R.id.team_detail_info);
		contactphon = (TextView) findViewById(R.id.team_detail_phone);
		inshare = (TextView) findViewById(R.id.team_detail_inshare);
		incollect = (TextView) findViewById(R.id.team_detail_incollect);
		
		storyText = (TextView) findViewById(R.id.team_detail_storytext);
		awardsText = (TextView) findViewById(R.id.team_detail_awardstext);
		title = (TextView) findViewById(R.id.team_detail_title);
		titleInfo = (TextView) findViewById(R.id.team_detail_title_info);
		
		vip = (ImageView) findViewById(R.id.team_detail_vip);
		zan = (ImageView) findViewById(R.id.team_detail_zan);
		
		pinfen = (TextView) findViewById(R.id.team_detail_pinfen);
		dianpins = (TextView) findViewById(R.id.team_detail_dianpin);
		souchang = (TextView) findViewById(R.id.team_detail_soucang);
		map = (ImageView) findViewById(R.id.team_detail_map);
		
		allwork = (TextView) findViewById(R.id.team_detail_allwork);
		allwork.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
		allwork.getPaint().setAntiAlias(true);//抗锯齿
		
		worklistview = (NoScrollListView) findViewById(R.id.team_detail_work);
		conmentlistview = (NoScrollListView) findViewById(R.id.team_detail_comment);
		workAdapter = new TeamLinGanAdapter(activity, worklist);
		conmentAdapter = new CommentAdapter(activity, conmentlist, true);
		worklistview.setAdapter(workAdapter);
		conmentlistview.setAdapter(conmentAdapter);
		worklistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				int position = new Long(arg3).intValue();
				JSONObject json = worklist.get(position);
				if(!StringUtil.isEmpty(BaseTools.getFrom("_id",json))&&!BaseTools.getFrom("_id",json).equals("-1")){
					Bundle data = new Bundle();
					data.putString("id", BaseTools.getFrom("_id",json));
					UIUtil.openActivity(activity, WorkDetailActivity.class, data);
				}else{
					UIUtil.ToastMessage(activity, "未找到该作品信息");
				}
			}
		});
		
		pinglun = (LinearLayout) findViewById(R.id.team_detail_pinglun);
		phone = (LinearLayout) findViewById(R.id.team_detail_shop);
				
		try {
			id = getIntent().getExtras().getString("id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
		share = new webCallBack() {
			@Override
			public void call(Object str) {
				UIUtil.showLoadingDialog(TeamDetailActivity.this, "加载中，请稍后...", false);
				appContext.showShare(URLs.SHARE_TEAM+"?id="+id);
			}
		};
		collect = new webCallBack() {
			@Override
			public void call(Object str) {
				if(!appContext.isLogin()){
					UIUtil.openActivity(TeamDetailActivity.this, LoginActivity.class, null,1);
				}else{
					Map<String, String> map = new HashMap<String, String>();
					map.put("auth_token", appContext.getLoginUid());
					map.put("target_id", id);
					final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "提交中，请稍后...", false);
					HttpService.postByText(collected?URLs.COLLECT_CANCEL_TEAM:URLs.COLLECT_TEAM, map, new TextHttpResponseHandler() {
						
						@Override
						public void onSuccess(int arg0, Header[] arg1, String arg2) {
							mProDialog.dismiss();
							try {
								JSONObject result = new JSONObject(arg2);
								if(result.getInt("status")==0){
									UIUtil.ToastMessage(activity, collected?"取消收藏成功":"收藏成功");
									collected = !collected;
									handler.sendEmptyMessage(2);
								}else{
									UIUtil.ToastMessage(activity, result.getString("message"));
								}
							} catch (JSONException e) {
								e.printStackTrace();
								UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
							}
						}
						
						@Override
						public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
							mProDialog.dismiss();
							UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
						}
					});
				}
			}
		};
		
		urlParam = new HashMap<String, String>();
		urlParam.put("id", id);
		loadData(urlParam);
	}
	
	@Override
	public void loadData(Map<String, String> param) {
		param.put("auth_token", appContext.getLoginUid());
		HttpService.getByText(URLs.TEAM_DETAIL, param, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					if(result.getInt("status")==0){
						Message  msg = new Message();
						Bundle data = new Bundle();
						data.putString("data", result.getJSONObject("data").toString());
						msg.setData(data);
						msg.what=1;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1&&appContext.isLogin()){
			loadData(urlParam);
//			url = url+"&auth_token="+appContext.getLoginUid();
//			Log.i("==web url==", url);
//			webView.loadUrl(url);  
		}
		if(requestCode==2&&resultCode==Activity.RESULT_OK&&null!=data){
			try {
				String pinlun = data.getStringExtra("comment");
				conmentlist.add(0, new JSONObject(pinlun));
				conmentAdapter.notifyDataSetChanged();
			} catch (JSONException e) {
				e.printStackTrace();
			}
//			handler.post(new Runnable() {
//				@Override
//				public void run() {
//					if(BuildConfig.DEBUG)Log.i("==comment==", data.getStringExtra("comment"));
//					webView.loadUrl("javascript:newComment('"+data.getStringExtra("comment")+"')");
//				}
//			});
		}
	}

	@Override
	public void clearData() {}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.team_detail_pinglun:
			Bundle bdl = new Bundle();
			bdl.putInt("type", 2);
			bdl.putString("id", id);
			UIUtil.openActivity(this, PinglunActivity.class, bdl, 2);
			break;
		case R.id.team_detail_inshare:
		case R.id.content_header_right_img:
			if(share!=null)share.call(null);
			break;
		case R.id.team_detail_shop:
			try {
				Intent intent=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+tel));
				startActivity(intent);
			} catch (Exception e) {
				UIUtil.ToastMessage(activity, "无法获取商家联系方式");
			}
			break;
		case R.id.team_detail_incollect:
		case R.id.content_header_right_img2:
			if(collect!=null)collect.call(null);
			break;
		default:
			break;
		}
	}

}
